<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { roomApi } from '../api/index'

const rooms = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加会议室')
const isEdit = ref(false)
const searchQuery = ref('')

const roomForm = ref({
  id: null,
  name: '',
  capacity: 0,
  location: '',
  equipment: '',
  status: 'AVAILABLE'
})

const roomFormRules = {
  name: [
    { required: true, message: '请输入会议室名称', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容纳人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '容纳人数必须大于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const roomFormRef = ref(null)

onMounted(async () => {
  await fetchRooms()
})

const fetchRooms = async () => {
  loading.value = true
  try {
    const res = await roomApi.getAllRooms()
    rooms.value = res.data
  } catch (error) {
    console.error('获取会议室列表失败:', error)
    ElMessage.error('获取会议室列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加会议室'
  isEdit.value = false
  dialogVisible.value = true
}

const handleEdit = (row) => {
  resetForm()
  dialogTitle.value = '编辑会议室'
  isEdit.value = true
  roomForm.value = {
    id: row.id,
    name: row.name,
    capacity: row.capacity,
    location: row.location || '',
    equipment: row.equipment || '',
    status: row.status
  }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该会议室吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await roomApi.deleteRoom(row.id)
      ElMessage.success('删除成功')
      await fetchRooms()
    } catch (error) {
      console.error('删除会议室失败:', error)
      ElMessage.error('删除会议室失败，请稍后重试')
    }
  }).catch(() => {})
}

const resetForm = () => {
  roomForm.value = {
    id: null,
    name: '',
    capacity: 0,
    location: '',
    equipment: '',
    status: 'AVAILABLE'
  }
  if (roomFormRef.value) {
    roomFormRef.value.resetFields()
  }
}

const submitForm = async () => {
  if (!roomFormRef.value) return
  
  await roomFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await roomApi.updateRoom(roomForm.value.id, roomForm.value)
          ElMessage.success('更新成功')
        } else {
          await roomApi.addRoom(roomForm.value)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        await fetchRooms()
      } catch (error) {
        console.error('操作失败:', error)
        if (error.response && error.response.data) {
          ElMessage.error(error.response.data.message || '操作失败，请稍后重试')
        } else {
          ElMessage.error('操作失败，请稍后重试')
        }
      }
    }
  })
}

// 过滤会议室列表
const filteredRooms = computed(() => {
  if (!searchQuery.value) return rooms.value
  
  const query = searchQuery.value.toLowerCase()
  return rooms.value.filter(room => 
    (room.name && room.name.toLowerCase().includes(query)) || 
    (room.location && room.location.toLowerCase().includes(query)) ||
    (room.status && room.status.toLowerCase().includes(query)) ||
    (room.capacity && room.capacity.toString().includes(query))
  )
})
</script>

<template>
  <div class="room-management-container">
    <div class="page-header">
      <h2>会议室管理</h2>
      <el-button type="primary" @click="handleAdd">添加会议室</el-button>
    </div>
    
    <el-card shadow="hover" class="filter-card">
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索会议室名称、位置、容量或状态"
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="table-card">
      <el-table
        v-loading="loading"
        :data="filteredRooms"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="capacity" label="容纳人数" width="100" />
        <el-table-column prop="location" label="位置" width="150" />
        <el-table-column prop="equipment" label="设备" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'AVAILABLE' ? 'success' : 'danger'">
              {{ scope.row.status === 'AVAILABLE' ? '可用' : '维护中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑会议室对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      append-to-body
    >
      <el-form
        ref="roomFormRef"
        :model="roomForm"
        :rules="roomFormRules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="roomForm.name" />
        </el-form-item>
        
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number v-model="roomForm.capacity" :min="1" :max="1000" />
        </el-form-item>
        
        <el-form-item label="位置" prop="location">
          <el-input v-model="roomForm.location" />
        </el-form-item>
        
        <el-form-item label="设备" prop="equipment">
          <el-input v-model="roomForm.equipment" type="textarea" :rows="3" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="roomForm.status" placeholder="请选择状态">
            <el-option label="可用" value="AVAILABLE" />
            <el-option label="维护中" value="MAINTENANCE" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.room-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input {
  max-width: 400px;
}

.table-card {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .search-input {
    width: 100%;
    max-width: none;
  }
}
</style>